package com.eastfair.pay.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eastfair.boot.request.PageParams;
import com.eastfair.boot.service.SuperServiceImpl;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.exception.BizException;
import com.eastfair.core.utils.ConvertUtil;
import com.eastfair.pay.dao.InvoiceApplyMapper;
import com.eastfair.pay.dto.InvoiceApplyDTO;
import com.eastfair.pay.dto.InvoiceApplyPageQuery;
import com.eastfair.pay.entity.*;
import com.eastfair.pay.enums.InvoiceStateEnum;
import com.eastfair.pay.exceptioncode.PayExceptionCode;
import com.eastfair.pay.service.*;
import com.eastfair.pay.vo.InvoiceApplyVO;
import com.eastfair.pay.vo.InvoiceVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;

/**
 * <p>
 * 业务实现类
 * 发票申请
 * </p>
 *
 * @author clm
 * @date 2022-06-08
 */
@Slf4j
@Service
public class InvoiceApplyServiceImpl extends SuperServiceImpl<InvoiceApplyMapper, InvoiceApply> implements InvoiceApplyService {

    @Autowired
    private InvoiceTitleService invoiceTitleService;
    @Autowired
    private SettlementService settlementService;
    @Autowired
    private ContractService contractService;
    @Autowired
    private InvoiceService invoiceService;
    /**
     * 处理逻辑删除相关处理
     *
     * @param modelList 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerRemoveByIdsOfLogic(Collection<InvoiceApply> modelList) {
        modelList.stream().forEach(s -> {
            s.setIsDeleted(BusinessConstant.YES);
        });
        // TODO: 2021/10/29 这里需要操作其他业务，如清空角色等
        return R.successDef();
    }
    /**
     * 基础数据
     * @param model
     * @return
     */
    @Override
    protected R<Boolean> handlerSave(InvoiceApply model) {
        model.setProjectId(ContextUtil.getProjectId());
        model.setSubsystemId(ContextUtil.getSubSystemId());
        model.setTenantId(ContextUtil.getTenantId());
        //雪花ID
        return R.successDef();
    }

    /**
     * 保存发票申请、发票抬头
     * @param invoiceApplyDTO
     * @return
     */
    @Override
    public void saveInvoiceApply(InvoiceApplyDTO invoiceApplyDTO) {
        //发票申请实例化对象
        InvoiceApply invoiceApply = new InvoiceApply();
        //对象复制
        BeanUtils.copyProperties(invoiceApplyDTO,invoiceApply);

        invoiceApply.setCutomerId(invoiceApplyDTO.getCutomerId());
        invoiceApply.setCutomerName(invoiceApplyDTO.getCutomerName());
        invoiceApply.setExhibitionId(invoiceApplyDTO.getExhibitionId());
        invoiceApply.setExhibitionName(invoiceApplyDTO.getExhibitionName());

        //申请人
        invoiceApply.setApplicationId(ContextUtil.getUserId());
        invoiceApply.setApplicationName(ContextUtil.getRealName());
        //发票抬头实例化对象
        InvoiceTitle invoiceTitle = new InvoiceTitle();
        //客户ID
        invoiceTitle.setCutomerId(invoiceApply.getCutomerId());
        //对象复制
        BeanUtils.copyProperties(invoiceApplyDTO,invoiceTitle);
        //开票状态
        invoiceApply.setInvoiceState(InvoiceStateEnum.INVOICING.getCode());
        log.info("invoiceApply++++12345:{}", ContextUtil.getRealName());
        log.info("invoiceApply++++12345:{}", ContextUtil.getUserId());
        log.info("invoiceApply++++:{}", JSONObject.toJSONString(invoiceApply));
        //保存相关对象
         save(invoiceApply);
        //查询发票抬头是否存在
        QueryWrapper<InvoiceTitle> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().like(!StrUtil.isBlank(invoiceApplyDTO.getInvoiceDutyParagraph()),InvoiceTitle::getInvoiceDutyParagraph,invoiceApplyDTO.getInvoiceDutyParagraph())
                .like(!StrUtil.isBlank(invoiceApplyDTO.getInvoiceTitle()), InvoiceTitle::getInvoiceTitle, invoiceApplyDTO.getInvoiceTitle());
        int count = invoiceTitleService.count(queryWrapper);
        //不存在保存发票抬头
        if(count == 0){
          invoiceTitleService.save(invoiceTitle);
        }

    }

    /**
     * 发票申请查询
     * @param params
     * @return
     */
    @Override
    public Page<InvoiceApplyVO> queryList(PageParams<InvoiceApplyPageQuery> params) {
        InvoiceApplyPageQuery invoiceApplyPageQuery = params.getModel();
        LambdaQueryWrapper<InvoiceApply> invoiceApplyLambdaQueryWrapper = new LambdaQueryWrapper<>();
        invoiceApplyLambdaQueryWrapper.eq(InvoiceApply::getIsDeleted,0);
//        applyRefundLambdaQueryWrapper.apply("DATE_FORMAT(create_time ,'%Y-%m-%d') <= "+applyRefundPageQuery.getRefundTime());

        //申请开票时间
        invoiceApplyLambdaQueryWrapper.ge(invoiceApplyPageQuery.getStartApplicationTime()!= null, InvoiceApply::getCreateTime,invoiceApplyPageQuery.getStartApplicationTime());
        invoiceApplyLambdaQueryWrapper.le(invoiceApplyPageQuery.getEndApplicationTime()!= null,InvoiceApply::getCreateTime,invoiceApplyPageQuery.getEndApplicationTime());
        //票据类型
        invoiceApplyLambdaQueryWrapper.eq(StrUtil.isNotEmpty(invoiceApplyPageQuery.getInvoiceType()),InvoiceApply::getInvoiceType,invoiceApplyPageQuery.getInvoiceType());
        //申请人员
        invoiceApplyLambdaQueryWrapper.eq(StrUtil.isNotEmpty(invoiceApplyPageQuery.getApplicationName()),InvoiceApply::getApplicationName,invoiceApplyPageQuery.getApplicationName());
        //经手人
        invoiceApplyLambdaQueryWrapper.eq(StrUtil.isNotEmpty(invoiceApplyPageQuery.getApplicantName()),InvoiceApply::getApplicantName,invoiceApplyPageQuery.getApplicantName());
        //查询类型ID
        invoiceApplyLambdaQueryWrapper.eq(null!=invoiceApplyPageQuery.getBusinessId(),InvoiceApply::getBusinessId,invoiceApplyPageQuery.getBusinessId());
        //业务ID
        invoiceApplyLambdaQueryWrapper.eq(null!=invoiceApplyPageQuery.getBusinessType(),InvoiceApply::getBusinessType,invoiceApplyPageQuery.getBusinessType());
        //税号
        invoiceApplyLambdaQueryWrapper.eq(StringUtils.isNotBlank(invoiceApplyPageQuery.getInvoiceDutyParagraph()),InvoiceApply::getInvoiceDutyParagraph,invoiceApplyPageQuery.getInvoiceDutyParagraph());

        //关键字
        invoiceApplyLambdaQueryWrapper.and(StrUtil.isNotEmpty(invoiceApplyPageQuery.getKeywords()), likeQueryWrapper -> likeQueryWrapper
                .like(InvoiceApply::getExhibitionName, invoiceApplyPageQuery.getKeywords())
                .or().like(InvoiceApply::getInvoiceTitle, invoiceApplyPageQuery.getKeywords())

        );
        //参数转化
        Page<InvoiceApply> applyRefundPage =params.buildPage();
        //查询
        Page<InvoiceApply> applyPage = page(applyRefundPage, invoiceApplyLambdaQueryWrapper);
        //实体转化
        Page<InvoiceApplyVO> invoiceApplyVOPage = ConvertUtil.convertPage(applyPage, InvoiceApplyVO.class);
        return invoiceApplyVOPage;
    }

    /**
     * 根据ID查询详情
     * @param invoiceApplyId
     * @return
     */
    @Override
    public InvoiceApplyVO invoiceApplyQueryById(Long invoiceApplyId) {
        //查询申请开票
        InvoiceApply invoiceApply = getById(invoiceApplyId);
        if(null == invoiceApply){
            throw new BizException(PayExceptionCode.INVOICE_DOES_NOT_EXIST.getMsg());
        }
        InvoiceApplyVO invoiceApplyVO = new InvoiceApplyVO();
        BeanUtils.copyProperties(invoiceApply,invoiceApplyVO);
        invoiceApplyVO.setCreateTime(invoiceApply.getCreateTime());
        //查询开票详情
        QueryWrapper<Invoice> invoiceQueryWrapper = new QueryWrapper<>();
        invoiceQueryWrapper.lambda().eq(Invoice::getInvoiceApplyId,invoiceApplyId);
        List<Invoice> invoiceList = invoiceService.list(invoiceQueryWrapper);
        //装在数据
        invoiceApplyVO.setInvoiceVOList( ConvertUtil.convertList(invoiceList, InvoiceVO.class));
        return invoiceApplyVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean cancelInvoiceApply(Long id) {
        log.info("cancelInvoiceApply - 取消发票申请, id={}", id);
        InvoiceApply invoiceApply = getById(id);
        if (invoiceApply == null) {
            throw BizException.wrap(-1, "发票申请不存在");
        }
        if (InvoiceStateEnum.INVOICE_SUCCESS.getCode().equals(invoiceApply.getInvoiceState())) {
            throw BizException.wrap(-1, "发票申请已开具成功，不可取消");
        }
        return removeById(id);
    }
}
